#!/bin/sh /etc/rc.common

START=99
STOP=01

DEFAULT_PACKAGES="luci-app-wechatpush luci-app-filemanager luci-i18n-package-manager-zh-cn luci-i18n-firewall-zh-cn vsftpd openssh-sftp-server luci-app-ttyd lucky tailscale luci-theme-aurora openlist2 luci-app-openclash luci-app-passwall2"
UPDATE_PATH="/usr/bin/auto-update.sh"
LOG_FILE="/tmp/auto-setup-$$.log"

# 批量初始化变量
for var in CRON_TIME INSTALL_PRIORITY SYS_ARCH ARCH_FALLBACK PKG_TYPE PKG_EXT PKG_INSTALL PKG_UPDATE PKG_LIST_INSTALLED PKG_LIST PKG_INFO INSTALLED_PACKAGES PENDING_PACKAGES FAILED_PACKAGES THIRD_PARTY_INSTALLED UNINSTALLED_PACKAGES REMAINING_PACKAGES; do
    eval "$var=''"
done

# 日志函数
log() {
    local msg="[$(date '+%Y-%m-%d %H:%M:%S')] $1"
    echo "$msg" | tee -a "$LOG_FILE"
    logger -t "auto-setup" "$1" 2>/dev/null || true
}

# 读取引导配置
read_fetch_config() {
    local script="/etc/init.d/auto-setup-fetch"
    [ ! -f "$script" ] && { log "⚠ 引导脚本不存在"; return 1; }
    
    eval "$(grep -E '^(CRON_TIME|INSTALL_PRIORITY|PACKAGES|AUTHORS|PUSH_TOKEN|EXCLUDE_PACKAGES)=' "$script" 2>/dev/null | sed 's/#.*//')"
    
    SCRIPT_URLS=$(. "$script" >/dev/null 2>&1; echo "$SCRIPT_URLS")

    [ -z "$PACKAGES" ] && PACKAGES="$DEFAULT_PACKAGES"
    
    log "🔍 识别配置: ${CRON_TIME:+定时:$CRON_TIME }${AUTHORS:+作者:$AUTHORS }${PUSH_TOKEN:+推送:开 }${EXCLUDE_PACKAGES:+排除:有 }URLs:$(echo $SCRIPT_URLS|wc -w)个"
}

# 检测包管理器
detect_package_manager() {
    log "检测包管理器..."
    
    if which opkg >/dev/null 2>&1; then
        PKG_TYPE="opkg"
        PKG_EXT=".ipk"
        PKG_INSTALL="opkg install"
        PKG_UPDATE="opkg update"
        PKG_LIST_INSTALLED="opkg list-installed"
        PKG_LIST="opkg list"
        PKG_INFO="opkg info"
    elif which apk >/dev/null 2>&1; then
        PKG_TYPE="apk"
        PKG_EXT=".apk"
        PKG_INSTALL="apk add --allow-untrusted"
        PKG_UPDATE="apk update"
        PKG_LIST_INSTALLED="apk info"
        PKG_LIST="apk search"
        PKG_INFO="apk info"
    else
        log "✗ 未找到包管理器"
        return 1
    fi
    
    log "√ 包管理器: $PKG_TYPE, 格式: $PKG_EXT"
}

# 架构变体映射
get_arch_variants() {
    case "$1" in
        aarch64_cortex-a53) echo "aarch64_cortex-a53 aarch64-cortex-a53 aarch64_generic aarch64 arm64" ;;
        aarch64_cortex-a72) echo "aarch64_cortex-a72 aarch64-cortex-a72 aarch64_generic aarch64 arm64" ;;
        aarch64_cortex-a76) echo "aarch64_cortex-a76 aarch64-cortex-a76 aarch64_generic aarch64 arm64" ;;
        aarch64_generic|aarch64) echo "aarch64_generic aarch64 arm64" ;;
        x86_64) echo "x86_64 x86-64 amd64" ;;
        mipsel_24kc) echo "mipsel_24kc mipsel mipsle" ;;
        arm_cortex-a*) echo "$1 armv7 arm_cortex-a9 arm_cortex-a7 armhf" ;;
        armv7|armhf) echo "armv7 arm_cortex-a9 arm_cortex-a7 armhf" ;;
        *) echo "$1" ;;
    esac
}

# 检测 Cortex 型号
detect_cortex() {
    local part=$(awk '/CPU part/ {print $4; exit}' /proc/cpuinfo 2>/dev/null)
    case "$part" in
        0xd03) echo "aarch64_cortex-a53" ;;
        0xd08) echo "aarch64_cortex-a72" ;;
        0xd0b) echo "aarch64_cortex-a76" ;;
        *)
            grep -qi "cortex-a53" /proc/cpuinfo && echo "aarch64_cortex-a53" && return
            grep -qi "cortex-a72" /proc/cpuinfo && echo "aarch64_cortex-a72" && return
            grep -qi "cortex-a76" /proc/cpuinfo && echo "aarch64_cortex-a76" && return
            echo "aarch64_generic"
            ;;
    esac
}

# 检测系统架构
detect_arch() {
    local base=""
    
    if [ "$PKG_TYPE" = "opkg" ]; then
        base=$(opkg print-architecture 2>/dev/null | awk '!/^arch (all|noarch)/ {print $2; exit}')
    elif [ "$PKG_TYPE" = "apk" ]; then
        base=$(apk --print-arch 2>/dev/null)
        [ "$base" = "aarch64" ] && base=$(detect_cortex)
    else
        base=$(uname -m)
        case "$base" in
            aarch64) base=$(detect_cortex) ;;
            armv7l) base="armv7" ;;
            mipsel) base="mipsel_24kc" ;;
        esac
    fi
    
    get_arch_variants "$base"
}

# 初始化架构
init_arch() {
    local list=$(detect_arch)
    SYS_ARCH=$(echo "$list" | awk '{print $1}')
    ARCH_FALLBACK="$list"
    
    log "系统架构: $SYS_ARCH"
    log "架构列表: $ARCH_FALLBACK"
}

# 保存配置
save_all_config() {
    local conf="/etc/auto-setup.conf"
    
    cat > "$conf" <<EOF
# 用户配置
CRON_TIME="${CRON_TIME:-}"
INSTALL_PRIORITY="${INSTALL_PRIORITY:-}"
AUTHORS="${AUTHORS:-}"
PUSH_TOKEN="${PUSH_TOKEN:-}"
EXCLUDE_PACKAGES="${EXCLUDE_PACKAGES:-}"
SCRIPT_URLS="${SCRIPT_URLS:-}"

# 系统信息（自动检测）
SYS_ARCH="$SYS_ARCH"
ARCH_FALLBACK="$ARCH_FALLBACK"
PKG_TYPE="$PKG_TYPE"
PKG_EXT="$PKG_EXT"

# 包管理器命令
PKG_INSTALL="$PKG_INSTALL"
PKG_UPDATE="$PKG_UPDATE"
PKG_LIST_INSTALLED="$PKG_LIST_INSTALLED"
PKG_LIST="$PKG_LIST"
PKG_INFO="$PKG_INFO"
EOF
    
    [ -f "$conf" ] && log "√ 配置已保存" || { log "✗ 配置保存失败"; return 1; }
}

# 检查已安装
is_installed() {
    $PKG_LIST_INSTALLED 2>/dev/null | grep -q "^$1 "
}

# 检查包存在
pkg_exists() {
    $PKG_LIST "$1" 2>/dev/null | grep -q "^$1"
}

# 安装语言包
install_lang() {
    local pkg="$1" lang=""
    
    case "$pkg" in
        luci-app-*) lang="luci-i18n-${pkg#luci-app-}-zh-cn" ;;
        luci-theme-*) lang="luci-i18n-theme-${pkg#luci-theme-}-zh-cn" ;;
        *) return ;;
    esac
    
    is_installed "$lang" && return
    pkg_exists "$lang" || return
    
    $PKG_INSTALL "$lang" >>"$LOG_FILE" 2>&1 && log "√ $lang 安装成功"
}

# 安装单个包
install_pkg() {
    local pkg="$1"
    [ -z "$pkg" ] && return 1
    
    log "  安装 $pkg..."
    
    $PKG_INSTALL "$pkg" >>"$LOG_FILE" 2>&1 && {
        log "√ $pkg 安装成功"
        INSTALLED_PACKAGES="$INSTALLED_PACKAGES $pkg"
        install_lang "$pkg"
        return 0
    } || {
        log "  ✗ $pkg 安装失败"
        return 1
    }
}

# 批量安装（官方源）
install_official() {
    local list="$1"
    log "从官方源安装..."
    [ -z "$list" ] && { log "无需安装"; return; }
    
    log "包数量: $(echo $list | wc -w) 个"
    
    local ok=0 fail=0 skip=0
    PENDING_PACKAGES=""
    
    for pkg in $list; do
        [ -z "$pkg" ] && continue
        
        is_installed "$pkg" && {
            log "⊝ $pkg 已安装"
            skip=$((skip+1))
        } || install_pkg "$pkg" && {
            ok=$((ok+1))
        } || {
            PENDING_PACKAGES="$PENDING_PACKAGES $pkg"
            fail=$((fail+1))
        }
    done
    
    PENDING_PACKAGES=$(echo "$PENDING_PACKAGES" | xargs)
    log "安装完成: 成功 $ok, 失败 $fail, 跳过 $skip"
    [ -n "$PENDING_PACKAGES" ] && log "失败包: $PENDING_PACKAGES"
}

# 下载 auto-update.sh
download_auto_update() {
    log "下载 auto-update.sh..."
    mkdir -p /usr/bin/
    
    for url in $SCRIPT_URLS; do
        local update_url=$(echo "$url" | sed 's/auto-setup.*/auto-update.sh/')
        
        curl -fsSL --max-time 5 -o "$UPDATE_PATH" "$update_url" 2>/dev/null || {
            log "  ✗ 下载失败: $update_url"
            rm -f "$UPDATE_PATH"
            continue
        }
        
        [ -f "$UPDATE_PATH" ] && [ -s "$UPDATE_PATH" ] || {
            log "  ✗ 文件无效"
            rm -f "$UPDATE_PATH"
            continue
        }
        
        grep -q "SCRIPT_VERSION" "$UPDATE_PATH" && grep -q "run_update" "$UPDATE_PATH" || {
            log "  ✗ 内容验证失败"
            rm -f "$UPDATE_PATH"
            continue
        }
        
        chmod +x "$UPDATE_PATH"
        log "√ 下载成功 ($(wc -c < "$UPDATE_PATH" | tr -d ' ') 字节)"
        return 0
    done
    
    log "✗ 所有源均下载失败"
    return 1
}

# 调用第三方安装
call_third_party() {
    local pkgs="$1"
    log "调用第三方源安装..."
    log "传递包数量: $(echo $pkgs | wc -w) 个"
    
    sh "$UPDATE_PATH" install $pkgs
    
    log "第三方源安装完成"
    THIRD_PARTY_INSTALLED=$(sed -n 's/^THIRD_PARTY_INSTALLED="\(.*\)"/\1/p' /etc/auto-setup.conf 2>/dev/null)
}

# 过滤未安装的包
filter_uninstalled() {
    local list="$1" verbose="$2"
    UNINSTALLED_PACKAGES=""
    local skip=0
    
    [ "$verbose" = "1" ] && log "检查已安装状态..."
    
    for pkg in $list; do
        [ -z "$pkg" ] && continue
        is_installed "$pkg" && skip=$((skip+1)) || UNINSTALLED_PACKAGES="$UNINSTALLED_PACKAGES $pkg"
    done
    
    UNINSTALLED_PACKAGES=$(echo "$UNINSTALLED_PACKAGES" | xargs)
    
    [ "$verbose" = "1" ] && {
        [ $skip -gt 0 ] && log "已跳过 $skip 个已安装包"
        [ -n "$UNINSTALLED_PACKAGES" ] && log "待安装: $(echo $UNINSTALLED_PACKAGES | wc -w) 个"
    }
}

# 执行安装流程
run_install() {
    filter_uninstalled "$PACKAGES" 1
    [ -z "$UNINSTALLED_PACKAGES" ] && { log "所有包已安装"; return; }
    
    local need="$UNINSTALLED_PACKAGES"
    log "需要安装: $need (策略: $([ "$INSTALL_PRIORITY" = "1" ] && echo "第三方优先" || echo "官方优先"))"
    
    if [ "$INSTALL_PRIORITY" = "1" ]; then
        download_auto_update && call_third_party "$need"
        filter_uninstalled "$need"
        [ -n "$UNINSTALLED_PACKAGES" ] && install_official "$UNINSTALLED_PACKAGES"
    else
        install_official "$need"
        filter_uninstalled "$need"
        [ -n "$UNINSTALLED_PACKAGES" ] && download_auto_update && call_third_party "$UNINSTALLED_PACKAGES"
    fi
    
    filter_uninstalled "$need"
    FAILED_PACKAGES="$UNINSTALLED_PACKAGES"
}

# 验证 CRON 格式
validate_cron() {
    [ -z "$1" ] && return 1
    [ $(echo "$1" | wc -w) -ne 5 ] && return 1
    echo "$1" | grep -qE '^[0-9\*\-\,\/]+ [0-9\*\-\,\/]+ [0-9\*\-\,\/]+ [0-9\*\-\,\/]+ [0-9\*\-\,\/]+$'
}

# 配置定时任务
setup_crontab() {
    validate_cron "$CRON_TIME" || {
        log "自动更新: 未启用"
        [ -n "$CRON_TIME" ] && log "  ⚠ CRON_TIME 格式错误: $CRON_TIME"
        return
    }
    
    log "配置自动更新: $CRON_TIME"
    (crontab -l 2>/dev/null | grep -v "$UPDATE_PATH"; echo "$CRON_TIME $UPDATE_PATH") | crontab - && \
        log "√ 定时任务已添加" || log "✗ 定时任务添加失败"
}

# 删除安装脚本
remove_self() {
    log "删除安装脚本..."
    
    local files="/etc/init.d/auto-setup /etc/init.d/auto-setup-fetch /etc/rc.d/S99auto-setup /etc/rc.d/K01auto-setup /etc/rc.d/S99auto-setup-fetch"
    
    for f in $files; do
        [ -f "$f" ] || [ -L "$f" ] && rm -f "$f" && log "  删除: $f"
    done
    if [ -z "$CRON_TIME" ]; then
        log "未设置自动更新，清理所有相关文件"
        rm -f "$UPDATE_PATH" && log "  删除: $UPDATE_PATH"
        rm -f "/etc/auto-setup.conf" && log "  删除: 配置文件"
    fi
    sleep 2
    
    local remain=""
    for f in /etc/init.d/auto-setup /etc/init.d/auto-setup-fetch; do
        [ -f "$f" ] && remain="$remain $f"
    done
    
    [ -z "$remain" ] && log "√ 脚本已删除" || { log "⚠ 残留: $remain"; return 1; }
    
    echo " $INSTALLED_PACKAGES $THIRD_PARTY_INSTALLED " | grep -q " luci-proto-wireguard " && {
        log "检测到 luci-proto-wireguard，10秒后重启..."
        sleep 10
        reboot
    }
}

# 主安装流程
run_setup() {
    log "开始自动配置 (PID: $$)"
    log "日志: $LOG_FILE"
    read_fetch_config
    detect_package_manager || return 1
    init_arch
    save_all_config || return 1
    log "开始更新软件源…"
    $PKG_UPDATE >>"$LOG_FILE" 2>&1 && log "√ 软件源已更新" || log "⚠ 软件源更新失败"
    
    run_install
    
    if [ -z "$FAILED_PACKAGES" ]; then
        log "√ 所有包安装成功"
        setup_crontab
        remove_self
    else
        log "⚠ 安装失败: $FAILED_PACKAGES"
        log "保留脚本等待重试"
    fi  
    log "配置完成，日志: $LOG_FILE"
}

start() {
    (run_setup) &
}

stop() {
    log "停止配置服务"
}
